let booklist = [
  { id: 1, name: "三国", author: "罗贯中", des: "三国时期英雄豪杰们的故事" },
];
let book = {}; //  单个book 数据

let queryBooks = (req, res) => {
  res.send({
    status: 200,
    msg: "success",
    booklist,
  });
};

let addBook = (req, res) => {
  let id = booklist[booklist.length - 1].id + 1;
  console.log(id);
  let postData = {
    id,
    ...req.body,
  };
  booklist.push(postData);
  res.send({
    status: 200,
    msg: "添加成功",
    booklist,
  });
};

let deleteBook = (req, res) => {
  let id = req.params.id;
  booklist = booklist.filter((val) => val.id != id);
  console.log(booklist);
  res.send({
    status: 200,
    msg: "删除成功",
    booklist,
  });
};

let queryBook = (req, res) => {
  let id = req.params.id;
  [book] = booklist.filter((val) => val.id == id);
  console.log(book);
  res.send(book);
};

let updateBook = (req, res) => {
  let data = req.body;
  let id = book.id;
  let newBook = {
    id,
    ...data,
  };

  booklist = booklist.map((val) => (id == val.id ? (val = newBook) : val));
  res.send({
    status: 200,
    msg: "更新成功",
    booklist,
  });
};

let booksControl = {
  queryBooks,
  addBook,
  deleteBook,
  queryBook,
  updateBook,
};

module.exports = booksControl;
